package com.emotion.recognition.client;

import ca.nanometrics.gflot.client.Axis;
import ca.nanometrics.gflot.client.DataPoint;
import ca.nanometrics.gflot.client.PlotModel;
import ca.nanometrics.gflot.client.SeriesHandler;
import ca.nanometrics.gflot.client.SimplePlot;
import ca.nanometrics.gflot.client.options.AxisOptions;
import ca.nanometrics.gflot.client.options.BarSeriesOptions;
import ca.nanometrics.gflot.client.options.BarSeriesOptions.BarAlignment;
import ca.nanometrics.gflot.client.options.GlobalSeriesOptions;
import ca.nanometrics.gflot.client.options.LegendOptions;
import ca.nanometrics.gflot.client.options.PlotOptions;
import ca.nanometrics.gflot.client.options.TickFormatter;

import com.emotion.recognition.shared.Emotion;
import com.google.gwt.user.client.ui.FlowPanel;

public class BarChart extends FlowPanel {
    private SimplePlot plot;
    private SeriesHandler handler;

    public BarChart() {
        PlotModel model = new PlotModel();
        PlotOptions plotOptions = new PlotOptions();

        BarSeriesOptions barSeriesOptions = new BarSeriesOptions();
        barSeriesOptions.setShow(true);
        barSeriesOptions.setLineWidth(1);
        barSeriesOptions.setBarWidth(0.6);
        barSeriesOptions.setAlignment(BarAlignment.CENTER);

        plotOptions.setGlobalSeriesOptions(new GlobalSeriesOptions()
                .setBarsSeriesOptions(barSeriesOptions));
        plotOptions.setLegendOptions(new LegendOptions().setShow(false));

        plotOptions.addYAxisOptions(new AxisOptions().setMinimum(0).setMaximum(1));
        plotOptions.addXAxisOptions(new AxisOptions().setMinimum(0).setMaximum(5).setTicks(4)
                .setTickFormatter(new TickFormatter() {
                    @Override
                    public String formatTickValue(double tick, Axis axis) {
                        if (tick >= 1 && tick <= 4) {
                            return Emotion.fromOrdinal((int) tick - 1).name();
                        }
                        return "";
                    }
                }));

        handler = model.addSeries("Probability", "blue");

        plot = new SimplePlot(model, plotOptions);
        this.add(plot);
    }

    public void setData(Double[] probs) {
        assert probs.length == 4;

        handler.clear();
        handler.add(new DataPoint(Emotion.ASTONISHED.ordinal() + 1, probs[3]));
        handler.add(new DataPoint(Emotion.CALM.ordinal() + 1, probs[2]));
        handler.add(new DataPoint(Emotion.SAD.ordinal() + 1, probs[1]));
        handler.add(new DataPoint(Emotion.SMILING.ordinal() + 1, probs[0]));

        // We don't need to draw because it's created before it is attached.
        // plot.redraw();
    }
}
